package mysql

import (
	"gorm.io/gorm"
	"house_srv/house"
)

type House struct {
	gorm.Model
	UserId      int64  `gorm:"type:int(11);comment:用户id"`
	AreaId      int64  `gorm:"type:int(11);comment:地区id"`
	Title       string `gorm:"type:varchar(100);comment:标题"`
	Price       int64  `gorm:"type:int(11);comment:价格"`
	Address     string `gorm:"type:varchar(100);comment:地址"`
	HouseNumber string `gorm:"type:varchar(30);comment:门牌号"`
	Floor       int64  `gorm:"type:varchar(50);comment:楼层"`
	RoomCount   int64  `gorm:"type:int(11);comment:房源数"`
	Acreage     int64  `gorm:"type:int(11);comment:面积"`
	Status      int64  `gorm:"type:tinyint(1);default:1;comment:状态:1:下架,2:上架"`
	CheckStatus int64  `gorm:"type:tinyint(1);default:1;comment:审核状态:1:待审核,2:审核通过,3:审核失败,"`
}

//设施表

type Facility struct {
	gorm.Model
	Name string `gorm:"type:varchar(100),not null;comment:'设施名称'"`
}

// 房屋设施表

type HouseFacility struct {
	gorm.Model
	HouseId    int `gorm:"type:int;index;comment:'房屋ID'"`
	FacilityId int `gorm:"type:int;comment:'设施ID'"`
}

// 房屋图片

type HouseImage struct {
	gorm.Model
	HouseId int    `gorm:"type:int;index;comment:'房屋ID'"`
	UrL     string `gorm:"type:varchar(255);not null;comment:'图片地址'"`
	Status  int    `gorm:"type:tinyint(1);default:1;comment:'状态:1:图片,2:视频'"`
}

// 修改审核状态
func (h *House) UpdateChecked() error {
	return Db.Model(&h).Where("id = ?", h.ID).Update("checked", h.CheckStatus).Error
}

// 修改房源状态
func (h *House) UpdateStatus() error {
	return Db.Model(&h).Where("id = ?", h.ID).Update("status", h.Status).Error
}

func (h *House) Create() error {
	return Db.Create(&h).Error
}

func (hf *HouseFacility) Create() error {
	return Db.Create(&hf).Error
}

func (hi *HouseImage) Create() error {
	return Db.Create(&hi).Error
}

func (h *House) HomeList(keyword string, page, pageSize, areaId, statusPrice, endPrice int64) (homeList []*house.HouseList, err error) {
	db := Db.Debug()
	if statusPrice > 0 {
		db = db.Where("price =>?", pageSize)
	}
	if endPrice > 0 {
		db = db.Where("price <=?", endPrice)
	}
	err = Db.Where("area_id = ?", areaId).Where("title like ?", "%"+keyword+"%").Where("status = 2 and check_status = 2").
		Order("creates_at desc").Scopes(Paginate(page, pageSize)).Find(&homeList).Error
	return
}
func Paginate(page, pageSize int64) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(int(offset)).Limit(int(pageSize))
	}
}
